package producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * @author 夏焰波
 * @date 2020-09-13 23:11
 */
public class PartitionProducer {
    public static void main(String[] args) {
        //1.创建Kafka生产者的配置信息
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //添加分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "partitioner.MyPartitioner");

        //2.创建生成者对象
        Producer<String, String> producer = new KafkaProducer<>(properties);
        for (int i = 0; i < 100; i++) {
            //3.发送数据
            producer.send(new ProducerRecord<String, String>("first", Integer.toString(i)),
                    (metadata, exception) -> {
                        if (exception == null) {
                            //offset从0开始
                            System.out.println(metadata.partition() + " -- " + metadata.offset());
                        } else {
                            exception.printStackTrace();
                        }
                    });
            //4.关闭资源，会清缓存
            producer.close();
        }
    }
}
